﻿using ERP.Common;
using ERP.ERPSystem.RBAC.Dto;
using ERP.Team.RBAC;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.UI;
using Volo.Abp.Users;

namespace ERP.ERPSystem.RBAC
{
    public class UserService : ApplicationService, IUserService
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IRepository<UserModel, int> _userrepository;
        /// <summary>
        /// 用户角色仓储
        /// </summary>
        private readonly IRepository<UserRoleModel, int> _userRoleModelrepository;
        /// <summary>
        /// 部门仓储
        /// </summary>
        private readonly IRepository<DepartmentModel, int> _departmentModelBps;
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="userrepository"></param>
        public UserService(IRepository<UserModel, int> userrepository, IRepository<UserRoleModel, int> userRoleModelrepository, IRepository<DepartmentModel, int> departmentModelBps)
        {
            _userrepository = userrepository;
            _userRoleModelrepository = userRoleModelrepository;
            _departmentModelBps = departmentModelBps;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        public async Task<LoginResultDto> LoginAsync(string userName, string password)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
                {
                    return new LoginResultDto
                    {
                        Success = false,
                        Message = "用户名和密码不能为空"
                    };
                }

                // 查询用户
                var user = await _userrepository.FirstOrDefaultAsync(u => u.UserName == userName);

                if (user == null)
                {
                    return new LoginResultDto
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                }

                // 验证密码
                if (!VerifyPassword(password, user.UserPassWord))
                {
                    return new LoginResultDto
                    {
                        Success = false,
                        Message = "用户名或密码错误"
                    };
                }

                return new LoginResultDto
                {
                    Success = true,
                    Message = "登录成功",
                    UserId = user.Id.ToString(),
                    UserName = user.UserName
                };
            }
            catch (Exception ex)
            {
                return new LoginResultDto
                {
                    Success = false,
                    Message = "登录失败，请稍后重试"
                };
            }
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        private bool VerifyPassword(string inputPassword, string storedPassword)
        {
            try
            {
                // TODO: 实现密码验证逻辑
                // 这里应该使用加密算法比较密码
                return inputPassword == storedPassword;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="userdto"></param>
        /// <returns></returns>
        public async Task<int> AddUser(UserDto userdto)
        {
            var user = ObjectMapper.Map<UserDto, UserModel>(userdto);
            var i = await _userrepository.InsertAsync(user);
            return i == null ? 0 : 1;
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserDto>> ShowUser()
        {

            var user = await _userrepository.GetListAsync();
            var departmentModel = await _departmentModelBps.GetListAsync();

            var userDto = from a in user
                          join b in departmentModel on a.DepartmentId equals b.Id
                          select new UserDto
                          {
                              Id = a.Id,
                              userName = a.UserName,
                              userPassWord = a.UserPassWord,
                              userNickName = a.UserNickName,
                              departmentId = b.Id,
                              departmentName = b.DepartmentName,
                              userPhone = a.UserPhone
                          };

            return userDto.ToList();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>返回是否删除成功</returns>
        public async Task<bool> DeleteUser(int id)
        {
            // 先检查用户是否存在
            var user = await _userrepository.FindAsync(m => m.Id == id);
            if (user == null)
            {
                return false; // 用户不存在
            }

            await _userrepository.DeleteAsync(user);
            return true; // 删除成功 
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="userdto"></param>
        /// <returns></returns>
        public async Task<int> UpdateUser(UserDto userdto)
        {
            try
            {
                var user = await _userrepository.GetAsync(userdto.Id);
                if (user == null)
                {
                    return 0;
                }
                user.UserName = userdto.userName;
                user.UserPhone = userdto.userPhone;
                user.UserNickName = userdto.userNickName;
                user.DepartmentId = userdto.departmentId;
                await _userrepository.UpdateAsync(user);
                return 1;
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        /// <summary>
        /// 用户分配角色
        /// </summary>
        /// <param name="iputUserRoleDto"></param>
        /// <returns></returns>
        public async Task<int> AddUserRole(IputUserRoleDto iputUserRoleDto)
        {
            try
            {

                await _userRoleModelrepository.DeleteDirectAsync(x => x.UserId.Equals(iputUserRoleDto.UserId));

                List<UserRoleModel> roleList = new List<UserRoleModel>();
                foreach (var item in iputUserRoleDto.RoleId)
                {
                    roleList.Add(new UserRoleModel
                    {
                        UserId = iputUserRoleDto.UserId,
                        RoleId = item
                    });
                }

                await _userRoleModelrepository.InsertManyAsync(roleList);

                return 1;
            }
            catch (Exception)
            {
                return 0;
            }

        }

        /// <summary>
        /// 获取角色编号
        /// </summary>
        /// <param name="uid">选择的用户</param>
        /// <returns>返回角色编号集合</returns>
        public async Task<List<int>> GetUserRole(int uid)
        {
            try
            {
                var urdList = await _userRoleModelrepository.GetListAsync(x => x.UserId.Equals(uid));
                var ridList = urdList.Select(x => x.RoleId);
                return ridList.ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
